/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.noah.controller;

import com.noah.model.UserModel;
import com.noah.config.LoadConfiguration;
import com.noah.service.UserService;
import com.noah.validation.LoginValidation;
import com.sun.tracing.dtrace.Attributes;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author ngoc.phan
 */
@Controller
public class LoginController {

    @Autowired
    private LoginValidation loginValidation;

//    @Autowired
//    public LoginController(LoginValidation loginValidation) {
//        this.loginValidation = loginValidation;
//    }
    UserService userService = (UserService) LoadConfiguration.loadJDBC().getBean("userDAO");

    @RequestMapping(value = "/loginform", method = RequestMethod.GET)
    public String showForm(ModelMap map) {
        UserModel loginform = new UserModel();
        map.addAttribute("loginForm", loginform);//"loginForm" matchs with commandName="loginForm" in login.jsp
        return "loginform";
    }

    @RequestMapping(value = "/loginform", method = RequestMethod.POST)
    public String processForm(ModelMap model,
        @ModelAttribute("loginForm") UserModel loginForm, BindingResult result){
        String userName = loginForm.getUserName();
        String password = loginForm.getPassword();
        loginValidation.validate(loginForm, result);
        if (result.hasErrors()) {
            return "loginform";
        }
        if (!userService.checkLogin(userName, password)) {

            //  model.addAttribute("loginwrong", "Please reenter your account info!");
            return "loginform";
        }
        model.addAttribute("loginForm", loginForm);
        return "loginsucces";
    }
}